package logic

import (
	"common/global"
	"context"
	"equipment_server/model"
	equipment "equipment_server/proto"
	"errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"

	"time"
)

func (e *EquipmentServer) GetPdf(ctx context.Context, req *equipment.GetPdfRequest) (*equipment.GetPdfResponse, error) {
	// 解析日期
	startDate, err := time.Parse("2006-01-02", req.StartDate)
	if err != nil {
		return nil, err
	}

	endDate, err := time.Parse("2006-01-02", req.EndDate)
	if err != nil {
		return nil, err
	}
	if startDate.After(endDate) {
		return nil, errors.New("起始时间不能晚于结束时间")
	}
	//校验1：只能查询一个月间隔的数据
	if endDate.Sub(startDate) > 31*24*time.Hour {
		return nil, errors.New("只能根据一个月的数据生成健康报告")
	}
	// 校验2：只能查询一年的数据（起始时间不能早于当前时间往前推一年）
	oneYearAgo := time.Now().AddDate(-1, 0, 0)
	if startDate.Before(oneYearAgo) {
		return nil, errors.New("相关数据只保存一年 ")
	}
	// 1. 检查用户是否绑定了设备
	bindingsCollection := global.MonGoDatabase.Collection("device_bindings")
	filterUserBinding := bson.M{
		"user_id": req.UserID,
	}
	var userBinding model.DeviceBinding
	err = bindingsCollection.FindOne(ctx, filterUserBinding).Decode(&userBinding)
	if err != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			// 用户未绑定设备
			return nil, errors.New("您尚未绑定设备，请先绑定设备后再查看健康数据")
		}
		// 其他数据库错误
		return nil, errors.New("查询设备绑定信息失败")
	}
	// 生成健康报告
	healthReport, err := GenerateHealthReport(global.MonGoDbClient, userBinding.DeviceID, startDate, endDate)
	if err != nil {
		return nil, err
	}
	path, err := GeneratePDF(healthReport)
	if err != nil {
		return nil, err
	}
	return &equipment.GetPdfResponse{FileUrl: path}, nil
}
